
<?php
	define("sql_error_reporting",true);

	/******************  MAIN BEGIN  ********************/
	//print "Hello There";
	$sql;
	$conn;
	// if this breaks, remove the "= array()"
	$apArr;
	$btArr;
	$localDevices;
	
	// json object for inside json array
	$jsonOFriends;
	
	//parse incoming json
	$data = file_get_contents('php://input');
	$json = json_decode($data);
	
	$wifiSize = $json -> wifiSize;
	$btSize = $json -> btSize;
	$cell = $json -> cell;
	$name = $json -> name;
	$uID = $json -> uID;
	//print "uID " . $uID. "\n";
	$btID = $json -> btID;
	//print "btID " . $btID. "\n";
	$wifiID = $json -> wifiID;
	//print "wifiID " . $wifiID. "\n";
	
	$totalVisible = 1 + ($wifiSize*2) + ($btSize*6);
	
	
	makeSQLConn();
	//print "inserting into phones";
	$insertPhoneSQL ="INSERT INTO tblPhones (name, uID, btID, wifiID) SELECT * FROM (SELECT '$name', '$uID','$btID', '$wifiID') AS tmp WHERE NOT EXISTS (     SELECT uID FROM tblPhones WHERE uID = '$uID' ) LIMIT 1";
	
	mysql_query($insertPhoneSQL,$conn);
	
	
	parseCell();
	parseJSONBT();
	parseJSONWifi();
	closeSQLConn();
	
	makeSQLConn();
	cellFriends();
	wifiFriends();
	btFriends();
	//friendMaker();
	makeJSON();
	closeSQLConn();
	
	
	/******************  MAIN END  ********************/

//////////////////////////////////////////////////////////////////////////////////////////////////////////
//******************************************************************************************************//
//******************************************************************************************************//
//******************************************************************************************************//
//******************************************************************************************************//
//////////////////////////////////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////
	/****************** FUNCTIONS  *******************/  
	///////////////////////////////////////////////////
	
	
	/****************** Connect to database *******************/
	function makeSQLConn()
	{
		global $conn;
		$conn = mysql_connect("nightmare.cs.uct.ac.za", "bdavies", "6u66l3sa23");
		if(!$conn)
		{
			if (sql_error_reporting) 
			{
				die ("Sql error of <b>".$_SERVER["SCRIPT_NAME"]."</b>. Call to `$TABLE` in ".__FILE__." on line: ".__LINE__."<br>".mysql_error()."<br><b>SQL:</b><br>$sql<br>");
			}
		}
		mysql_select_db("bdavies", $conn);
	}
	
		
	/****************** closedata base connection *******************/
	function closeSQLConn()
	{
		global $conn;
		mysql_close($conn);
	}
	
	/****************** parse cell Json element *******************/
	function parseCell()
	{
		global $conn;
		global $cell;
		global $uID;	
		mysql_query("DELETE FROM tblCell WHERE (uID = '$uID')", $conn);
		$insertCellStmt = "INSERT INTO tblCell (uID, cellID) SELECT * FROM (SELECT '$uID','$cell') AS tmp WHERE NOT EXISTS (     SELECT uID FROM tblCell WHERE ((uID = '$uID') AND (cellID = '$cell')) ) LIMIT 1";
		mysql_query($insertCellStmt, $conn);
	}
	
	/****************** Parse Bluetooth JSON array *******************/
	function parseJSONBT()
	{
		//print "in parseJSONBT()";
		global $uID;
		global $conn;
		global $json;
		global $btArr;
		//parse local bluetooth device and put them in an array
		foreach($json->bluetooth as $service)
		{	
			//print "in first for loop";
 			print $services;
			$btArr[] = $service;
			
		}
			reset($btArr);
		
		// update tableAP : delete old entries,
		//print "Deleting";
		mysql_query("DELETE FROM tblBTDevices WHERE (uID = '$uID')", $conn);
		
		// run through wifiAP array
		foreach ($btArr as $item)
		{	
			
			//print "inserting";
			//  add new entries
			$insertAPSQL = "INSERT INTO tblBTDevices (uID, BTmac) SELECT * FROM (SELECT '$uID','$item') AS tmp WHERE NOT EXISTS (     SELECT uID FROM tblBTDevices WHERE ((uID = '$uID') AND (BTmac = '$item')) ) LIMIT 1";
			mysql_query($insertAPSQL,$conn);
		}
	}
	
	/****************** parse WIFI JSON array *******************/
	function parseJSONWifi()
	{
	//print "in parseJSONWifi()";
		global $uID;
		global $conn;
		global $json;
		global $apArr;
		//parse local wifi AP and put them in an array
		foreach($json->wifi as $service)
		{	
			$apArr[] = $service;
			
		}
			reset($apArr);
		
		// update tableAP : delete old entries,
		mysql_query("DELETE FROM tblAP WHERE (uID = '$uID')", $conn);
		
		// run through wifiAP array
		foreach ($apArr as $item)
		{	
			
			
			//  add new entries
			$insertAPSQL = "INSERT INTO tblAP (uID, APmac) SELECT * FROM (SELECT '$uID','$item') AS tmp WHERE NOT EXISTS (     SELECT uID FROM tblAP WHERE ((uID = '$uID') AND (APmac = '$item')) ) LIMIT 1";
			mysql_query($insertAPSQL,$conn);
		}
	}
	
/************************************/
 
/****************** ******************/

/****************** ******************/


/************************************/

/******************  ******************/

	/****************** find friends in Cell range ******************/
	function cellFriends()
	{
		global $localDevices;
		global $cell;
		global $name;
		global $conn;
		// select only those devices that share your cell tower
		$cellTable = mysql_query("SELECT uID FROM tblCell uID WHERE (cellID = '$cell')", $conn);
			//print "after uID select \n";
			
			// access each of those devices from the localDeviceTable object
			while($row = mysql_fetch_array($cellTable))
			{
				//print "in While loop \n";
				// set each to a variable 
				$rowUID = $row['uID'];
				//print "each row ofDeviceTable " . $rowUID ."\n";
				// select the wifiMAC of each
				$localDeviceCell = mysql_query("SELECT name FROM tblPhones WHERE( uID = '$rowUID')", $conn);
				// access each of those macs from the localDeviceWIFI object
				$count;
				while($cellIDNum = mysql_fetch_array($localDeviceCell))
				{
				
					//print "getting from table";
					$deviceName = $cellIDNum['name'];
					//print $deviceName . " is not the same as " . $name;
					if($deviceName != $name)
					{
						$localDevices[$deviceName] = 1;
					}
					
				}
			
			}
		
		
	}
	
	/****************** find friends in Wifi range ******************/
	function wifiFriends()
	{
		global $uID;
		global $conn;
		global $json;
		global $wifiID;
		global $name;
		global $apArr;
		global $btArr;
		global $localDevices;
		
		
		foreach ($apArr as $item)
		{	
			$wifiTable = mysql_query("SELECT uID FROM tblAP uID WHERE (APmac = '$item')", $conn);
			//print "after uID select \n";
			
			// access each of those devices from the localDeviceTable object
			while($row = mysql_fetch_array($wifiTable))
			{
				//print "in While loop \n";
				// set each to a variable 
				$rowUID = $row['uID'];
				//print "each row ofDeviceTable " . $rowUID ."\n";
				// select the wifiMAC of each
				$localDeviceWifi = mysql_query("SELECT name FROM tblPhones WHERE( uID = '$rowUID')", $conn);
				// access each of those macs from the localDeviceWIFI object
				$count;
				while($apMac = mysql_fetch_array($localDeviceWifi))
				{
				
					//print "getting from table \n";
					$deviceName = $apMac['name'];
					//print $deviceName . " is not qula to " . $name;
					if($deviceName != $name)
					{
						$temp = $localDevices[$deviceName];
						//print "yo: " . $temp /"\n";
						$localDevices[$deviceName] = $temp + 4;
					}
					
				}
				
			}
		}
		
	}
	
	/****************** find friends in Bluetooth range ******************/
	function btFriends()
	{
		global $uID;
		global $conn;
		global $json;
		global $wifiID;
		global $name;
		global $btID;
		global $btArr;
		global $localDevices;
		
		
		foreach ($btArr as $item)
		{	
			$btTable = mysql_query("SELECT uID FROM tblBTDevices uID WHERE (BTmac = '$item')", $conn);
			//print "after uID select \n";
			$btTableSelf = mysql_query("SELECT name FROM tblPhones WHERE(btID = '$item')", $conn);
			while($row = mysql_fetch_array($btTableSelf))
			{
				$rowName = $row['name'];
				$temp = $localDevices[$rowName];
				//print "yo: " . $temp /"\n";
				$localDevices[$rowName] = $temp + 20;
			}
			
			// access each of those devices from the localDeviceTable object
			while($row = mysql_fetch_array($btTable))
			{
				//print "in While loop \n";
				// set each to a variable 
				$rowUID = $row['uID'];
				//print "each row ofDeviceTable " . $rowUID ."\n";
				// select the wifiMAC of each
				$localDeviceBT = mysql_query("SELECT name FROM tblPhones WHERE( uID = '$rowUID')", $conn);
				// access each of those macs from the localDeviceWIFI object
				$count;
				while($btMac = mysql_fetch_array($localDeviceBT))
				{
				
					//print "getting from table \n";
					$deviceName = $btMac['name'];
					//print $deviceName . " is not qula to " . $name;
					if($deviceName != $name)
					{
						$temp = $localDevices[$deviceName];
						//print "yo: " . $temp /"\n";
						$localDevices[$deviceName] = $temp + 20;
					}
					
				}
				$count = sizeof($localDevices);
				
			}
		}
	}
	/****************** find and rank friends *******************/
	function friendMaker()
	{
		//print "in friendMaker()";
		global $uID;
		global $conn;
		global $json;
		global $apArr;
		global $btArr;
		global $localDevices;
		
				
		
	} 
	
	/****************** Write JSON to be returned to Phone *******************/
	function makeJSON()
	{
		//print "makeJSON()";
		global $localDevices;
		
		$jsonOFriends = array("friends" => array());
		$localDeviceString;
		$localDeviceNames = array_keys($localDevices);
		$count = sizeof($localDeviceNames);
		if($count == 0)
		{
			$noFriendString = "your phone has no friends here";
			$jsonOindividual = array("name" => $noFriendString,
			"value" => "");
			array_push($jsonOFriends["friends"], $jsonOindividual);
		}
		
		else
		{
			foreach($localDeviceNames as $friend)
			{
				$friendRating = ($localDevices[$friend]);
				$circle = dunbar($friendRating);
				$jsonOindividual = array(
				"name" => $friend,
				"value" => $circle);
				array_push($jsonOFriends["friends"], $jsonOindividual);
			}
		}
		header('Content-type: application/json');
		echo json_encode($jsonOFriends);
	}
	
	function dunbar($rating)
	{
		global $totalVisible;
		//$ratio = $rating/$totalVisible;
		
		if($rating == 1)
		{
			return "Same neighbourhood";
		}
		else if($rating >= 19)
		{
			return "Same Room";
		}
		else if(($rating > 1) && ($rating <= 6))
		{
			return "Same block";
		}
		else 
		{
			return "Same Building";
		}
	}

	
	
	/****************** test database connection *******************/
	function testDB()
	{
		global $sql;
		$sql = "CREATE TABLE Persons
		(
		FirstName varchar(15),
		LastName varchar(15),
		Age int
		)";
		//print "Charles McFilly";
	}
	
?>